//
//  FMResouceDownLoader.m
//  FMRemotePlayer
//
//  Created by apple on 17/3/14.
//  Copyright © 2017年 appbanana. All rights reserved.
//

#import "FMResouceDownLoader.h"
#import "FMRemotePlayerFile.h"

@interface FMResouceDownLoader ()<NSURLSessionDataDelegate>

@property (nonatomic, strong) NSURLSession *session;


@property (nonatomic, strong) NSOutputStream *stream;

@end

@implementation FMResouceDownLoader

- (void)downLoadWithUrl:(NSURL *)url offset:(long long)offset;
{
    self.url = url;
    self.offset = offset;
    [self cancleAndClean];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:0];
    [request setValue:[NSString stringWithFormat:@"bytes=%lld-", offset] forHTTPHeaderField:@"Range"];
    NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request];
    [task resume];
}

- (void)cancleAndClean{
    [self.session invalidateAndCancel];
    self.session = nil;
    [FMRemotePlayerFile removeTempFileWithURL:self.url];
    self.loadSize = 0;
    self.offset = 0;
}

#pragma mark------NSURLSessionDataDelegate

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSHTTPURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{
    
    NSLog(@"----response = %@", response);
    NSDictionary *infoDic = response.allHeaderFields;
    self.contentType = infoDic[@"Content-Type"];
    self.totalSize = [[infoDic[@"Content-Range"] componentsSeparatedByString:@"/"].lastObject longLongValue];
    self.stream = [NSOutputStream outputStreamToFileAtPath:[FMRemotePlayerFile tempAudioFilePath:self.url] append:YES];
    [self.stream open];

    completionHandler(NSURLSessionResponseAllow);
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(receiveNewData)]) {
        [self.delegate receiveNewData];
    }
    self.loadSize += data.length;
    [self.stream write:data.bytes maxLength:data.length];
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    [self.stream close];
    if (error == nil) {
        if (self.loadSize == self.totalSize) {
            [FMRemotePlayerFile moveTmpFileToCacheFileWithURL:self.url];
        }
    }
}

#pragma mark----seter geter------
- (NSURLSession *)session{
    if (!_session) {
        _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue new]];
    }
    return _session;
}


/*
 <AVAssetResourceLoadingRequest: 0x60800000e830, URL request = <NSMutableURLRequest: 0x6000000060e0> { URL: fm://audio.xmcdn.com/group22/M0B/60/85/wKgJM1g1g0ShoPalAJiI5nj3-yY200.m4a }, request ID = 1, content information request = <AVAssetResourceLoadingContentInformationRequest: 0x600000006120, content type = "(null)", content length = 0, byte range access supported = NO, disk caching permitted = NO, renewal date = (null)>, data request = <AVAssetResourceLoadingDataRequest: 0x608000005000, requested offset = 0, requested length = 2, requests all data to end of resource = NO, current offset = 0>>
 2017-03-12 21:18:01.281
 */
@end
